<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()

const formData = ref({
  username: '',
  password: '',
  verificationCode: ''
})

const loading = ref(false)
const error = ref('')
const captchaUrl = ref('')
const captchaKey = ref('')

const refreshCaptcha = async () => {
  try {
    const response = await axios.get('/api/User/captcha')
    // 确保验证码图片数据包含base64前缀
    captchaUrl.value = response.data.captchaImage.startsWith('data:image')
      ? response.data.captchaImage
      : `data:image/png;base64,${response.data.captchaImage}`
    captchaKey.value = response.data.captchaKey
  } catch (err) {
    console.error('获取验证码失败:', err)
    error.value = '获取验证码失败，请刷新页面重试'
  }
}

const handleLogin = async () => {
  // 表单验证
  if (!formData.value.username || !formData.value.password || !formData.value.verificationCode) {
    error.value = '请填写所有必填字段'
    return
  }

  try {
    loading.value = true
    error.value = ''
    
    const response = await axios.post('/api/User/login', {
      username: formData.value.username,
      password: formData.value.password,
      verificationCode: formData.value.verificationCode,
      captchaKey: captchaKey.value
    })

    // 登录成功后服务器返回token
    if (response.data.token) {
      localStorage.setItem('token', response.data.token)
      router.push('/')
    }
  } catch (err) {
    error.value = err.response?.data?.message || '登录失败，请重试'
    console.error('登录失败:', err)
    // 登录失败时刷新验证码
    refreshCaptcha()
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  refreshCaptcha()
})
</script>

<template>
  <div class="login-container">
    <form @submit.prevent="handleLogin" class="login-form">
      <h2>用户登录</h2>
      
      <div class="form-group">
        <label for="username">用户名</label>
        <input
          id="username"
          v-model="formData.username"
          type="text"
          placeholder="请输入用户名"
          required
        >
      </div>

      <div class="form-group">
        <label for="password">密码</label>
        <input
          id="password"
          v-model="formData.password"
          type="password"
          placeholder="请输入密码"
          required
        >
      </div>

      <div class="form-group">
        <label for="verificationCode">验证码</label>
        <div class="verification-code-container">
          <input
            id="verificationCode"
            v-model="formData.verificationCode"
            type="text"
            placeholder="请输入验证码"
            required
          >
          <img 
            :src="captchaUrl" 
            alt="验证码" 
            class="verification-code-image"
            @click="refreshCaptcha"
            style="cursor: pointer;"
            title="点击刷新验证码"
          >
        </div>
      </div>

      <div v-if="error" class="error-message">
        {{ error }}
      </div>

      <button type="submit" :disabled="loading">
        {{ loading ? '登录中...' : '登录' }}
      </button>
    </form>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: var(--color-background);
}

.login-form {
  width: 100%;
  max-width: 400px;
  padding: 2rem;
  background-color: var(--color-background-soft);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-form h2 {
  text-align: center;
  margin-bottom: 2rem;
  color: var(--color-heading);
}

.form-group {
  margin-bottom: 1.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  color: var(--color-text);
}

input {
  width: 100%;
  padding: 0.75rem;
  border: 1px solid var(--color-border);
  border-radius: 4px;
  background-color: var(--color-background);
  color: var(--color-text);
}

input:focus {
  outline: none;
  border-color: var(--color-border-hover);
}

.verification-code-container {
  display: flex;
  gap: 1rem;
}

.verification-code-container input {
  flex: 1;
}

.verification-code-image {
  width: 100px;
  height: 40px;
  border: 1px solid var(--color-border);
  border-radius: 4px;
}

.error-message {
  color: #dc3545;
  margin-bottom: 1rem;
  text-align: center;
}

button {
  width: 100%;
  padding: 0.75rem;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

button:hover:not(:disabled) {
  background-color: #45a049;
}
</style>